﻿function ProjectViewModel(model) {
    var selfModel = this;
    var isMain = true;

    selfModel.Controller = "Project";
    selfModel.StartPage = selfModel.Controller + "Info";

    ko.mapping.fromJS(model, {}, selfModel);

    selfModel.prototype = new CRUDViewModel(selfModel);


    Main.State.Hashes.push("Benefit");
    Main.State.Hashes.push("BenefitCreate");

    selfModel.BenefitViewModel = new BenefitViewModel(selfModel.BenefitViewModel);

    selfModel.TextEditorCreate = new TextEditorViewModel();
    selfModel.TextEditorCreate.Init("editorContainerCreate", "resultContainerCreate");

    selfModel.TextEditorUpdate = new TextEditorViewModel();

    selfModel.SelectItem = function (action, item) {
        selfModel.SelectedItem(item);

        //console.log('beneficios');
        //console.log(item.Benefits());
        //selfModel.Entity.Benefits(item.Benefits());
        //console.log('Beneficios entity');
        //console.log(selfModel.Entity.Benefits());

        //selfModel.BenefitViewModel.List(item.Benefits());
        //console.log('Beneficios Benefitsviewmodel');
        //console.log(selfModel.BenefitViewModel.List());

        //selfModel.BenefitViewModel.List(selfModel.Entity.Benefits());

        selfModel.BenefitViewModel.setProjectId(item.Id);
        selfModel.GetHtml(selfModel.SelectedItem().Id(), function () {
            if (action == selfModel.Controller + 'Update') {
                selfModel.TextEditorUpdate.Init("editorContainerUpdate", "resultContainerUpdate");
                selfModel.TextEditorUpdate.EditorObject().setData(selfModel.SelectedItem().Html());
            }
        });

        Main.Page.ChangeHash(action + "/" + item.Id());
    };

    selfModel.ResetForm = function () {
        selfModel.TextEditorCreate.EditorObject().setData("");

        selfModel.Entity.CategoryId(null);

        selfModel.base.ResetForm();
    };

    selfModel.FileUploaderChange = function (e, element) {
        var reader = new FileReader();
        var input = element.target;
        var preview = $(input).parent().parent().find('.filePreview');
        var fileName = $(input).parent().parent().find('.fileName');

        try {
            if (input.files.length > 0) {
                reader.onload = function (e) {
                    $(preview).attr('src', e.target.result);
                };
                reader.readAsDataURL(input.files[0]);
                $(fileName).val(input.files[0].name);
            }
        } catch (e) {
            console.log("Image preview error");
        }
    };

    selfModel.GetHtml = function (id, callBack) {
        var method = whoever.AJAX.Method({
            data: ko.toJSON({ 'id': id }),
            action: "../" + selfModel.Controller + "/GetHtml"
        });

        method.success(function (html) {
            if (html)
                selfModel.SelectedItem().Html(html);
            if (callBack)
                callBack();
        });
    };

    selfModel.UploadImage = function (callback) {
        if ($(".create .file")[0].files.length > 0) {
            var image = new FormData();
            image.append("file", $(".create .file")[0].files[0]);

            $.ajax({
                async: true,
                type: 'POST',
                url: '/FileUpload/UploadImage',
                data: image,
                dataType: "json",
                success: function (data) {
                    selfModel.Entity.Image(data.file);
                    callback();
                },
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
            callback();
        }
    };

    selfModel.UpdateImage = function (callback) {
        if ($(".update .file")[0].files.length > 0) {
            var data = new FormData();
            data.append("file", $(".update .file")[0].files[0]);
            data.append("relativePath", viewModel.SelectedItem().Image());

            $.ajax({
                async: true,
                type: 'POST',
                url: '/FileUpload/UpdateImage',
                data: data,
                dataType: "json",
                success: function (data) {
                    viewModel.SelectedItem().Image(data.file);
                    callback();
                },
                error: function (result) {
                    console.log(result);
                },
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
            callback();
        }
    };

    selfModel.Create = function () {
        selfModel.UploadImage(function () {
            selfModel.Entity.UserId();
            selfModel.Entity.Html(selfModel.TextEditorCreate.EditorObject().getData());
            selfModel.Entity.Benefits(selfModel.BenefitViewModel.List());
            selfModel.base.Create();
        });
    };

    selfModel.Update = function () {
        selfModel.UpdateImage(function () {
            selfModel.SelectedItem().Html(selfModel.TextEditorUpdate.EditorObject().getData());
            selfModel.base.Update();
        });
    };

    selfModel.Delete = function () {
        selfModel.base.Delete();
    };

    selfModel.Init(isMain);
}